package shop;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class CreateProductService implements CreateProduct {
	private JdbcTemplate db;
	
	@Autowired
	public void setDateSource(DataSource dataSource){
		this.db = new JdbcTemplate(dataSource);
	}
	
	public boolean createProduct(Product product){
		boolean result = false;
		try{
			if(existProductID(product.getId())){
			db.update("insert into product (id, name, price) values(?,?,?)", new Object[]{product.getId(), product.getName(), product.getPrice()});
			result = true;
			}else{
				throw new DuplicateProductException();
			}
		}catch(RuntimeException e){
			throw e;
		}
		return result;
	}
	
	private boolean existProductID(long ProductID){
		return db.queryForInt("select count(*) from product where id = ?", new Object[]{ProductID}) == 0;
	}
}
